package com.ssm.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

import javax.servlet.http.HttpServletRequest;

public abstract class IpUtil {

	/**
	 * 获取客户端IP地址
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取客户端MAC地址
	 * @param ipAddress
	 * @return
	 */
	public static String getMacAddress(String ipAddress) {
		Process process = null;
		String str = "";
		String macAddress = "";
		try {
			if(System.getProperty("os.name").toLowerCase().indexOf("window") != -1){
				process =Runtime.getRuntime().exec("nbtstat -A " + ipAddress);
	        }
			if (process != null) {
				InputStreamReader isr = new InputStreamReader(process.getInputStream());  
	            LineNumberReader lnr = new LineNumberReader(isr);
	            for (int i = 1; i < 100; i++) {
	                str = lnr.readLine();  
	                if (str != null) {
	                    if (str.indexOf("MAC") > 1) {
	                        macAddress = str.substring(str.length() - 17, str.length());  
	                        break;
	                    }
	                }
	            }
	            lnr.close();
	            isr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return macAddress;
	}
}
